<!--
 * @Author: caiwenfeng
 * @Date: 2024-05-13 10:25:55
 * @LastEditors: caiwenfeng
 * @LastEditTime: 2025-07-17 18:59:04
 * @Description: 悬浮按钮
-->
<template>
  <view
    class="u-fab"
    @touchstart.stop.prevent="handleTouchStart"
    @touchmove.stop.prevent="handleTouchmove"
    @touchend.stop.prevent="handleTouchend"
    :style="{
      bottom: `${position.bottom * 2}rpx`,
      right: `${position.right * 2}rpx`,
      color: color,
    }"
    @click="$emit('click')"
  >
    <image src="@/assets/images/consultant.png" class="w-[92rpx] h-[92rpx]" />
    <text>{{ text }}</text>
  </view>
</template>

<script setup>
  defineOptions({
    name: 'u-fab',
  });
  const props = defineProps({
    icon: {
      // 可支持uniapp的图标，以及iconfont的图标
      default: 'plusempty',
      type: String,
    },
    text: {
      default: '',
      type: String,
    },
  });
  const position = ref({
    bottom: 150,
    right: 10,
  });
  let downEvent = {
    clientX: 0,
    clientY: 0,
  };
  let isMoving = false;
  const emit = defineEmits(['click']);

  let windowInfo = {};
  // 鼠标按下事件
  const handleTouchStart = (e) => {
    console.log(1);
    const { clientX, clientY } = e.changedTouches[0];
    downEvent.clientX = clientX;
    downEvent.clientY = clientY;
  };

  // 移动事件
  const handleTouchmove = (e) => {
    const { clientX, clientY } = e.changedTouches[0];
    const { clientX: x, clientY: y } = downEvent;
    const moveX = (x - clientX).toFixed(2);
    const moveY = (y - clientY).toFixed(2);
    if (Math.abs(moveX) < 5 && Math.abs(moveY) < 5) {
      return;
    }
    isMoving = true;
    position.value.bottom += Number(moveY);
    position.value.right += Number(moveX);
    // 边界值校验
    if (position.value.bottom < 0) {
      position.value.bottom = 0;
    }
    if (position.value.right < 0) {
      position.value.right = 0;
    }
    if (position.value.right > windowInfo.windowWidth - 95) {
      position.value.right = windowInfo.windowWidth - 95;
    }
    if (position.value.bottom > windowInfo.windowHeight - 190) {
      position.value.bottom = windowInfo.windowHeight - 190;
    }
    downEvent.clientX = clientX;
    downEvent.clientY = clientY;
  };
  // 鼠标弹起事件
  const handleTouchend = () => {
    if (isMoving) {
      isMoving = false;
      return;
    }
    emit('click');
  };

  onMounted(() => {
    windowInfo = uni.getWindowInfo(); // 获取设备可视区域的数据
  });
</script>

<style lang="scss" scoped>
  .u-fab {
    width: 144rpx;

    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16rpx;
    justify-content: center;
    position: fixed;
    background:
      linear-gradient(180deg, rgba(253, 127, 28, 0.21) 0%, rgba(253, 132, 29, 0) 100%), #ffffff;
    box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(70, 26, 9, 0.18);
    border-radius: 16rpx;
    border: 2rpx solid rgba(255, 255, 255, 1);
    color: #ff800e;
    padding: 28rpx 0rpx 16rpx;
    text {
      font-size: 26rpx;
      font-weight: 600;
    }
  }
</style>
